package com.samapp.indent;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.samapp.MyApplication;
import com.samapp.R;
import com.samapp.base.BaseActivity;
import com.samapp.entity.Indent;
import com.samapp.utils.json.GsonUtil;

/**
 * 订单管理Activity
 */
public class IndentManageActivity extends BaseActivity implements OnClickListener {

	private MyApplication myApplication = MyApplication.getApplicationInstance();
	private Button btnBack = null;
	private Button btnAdd = null;
	private Button btnDelete = null;
	private Button btnSearch = null;
	private EditText editTextSearch = null;
	private PullToRefreshListView mPullToRefreshListView = null;
	private IndentAdapter mIndentAdapter = null;
	/**
	 * 订单数组
	 */
	private List<Indent> mIndents = new ArrayList<Indent>();
	/** 每页显示条数 */
	private int numPerPage = 10;
	/** 页面编号 */
	private int pageNum = 0;
	/** 是否加载完所有记录 */
	private boolean isLoadAllRecord = false;
	/** 是否下拉操作 */
	boolean isPullDownToRefresh = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.indent_manage);
		init();
		getIndentList();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		Log.i("Long", "重新获取焦点");
		getIndentList();
	}

	private void init() {
		initView();
		initPullToRefreshListView();
		initListener();
	}

	private void initView() {
		btnBack = (Button) findViewById(R.id.btn_back);
		btnAdd = (Button) findViewById(R.id.btn_add);
		btnDelete = (Button) findViewById(R.id.btn_delete);
		btnSearch = (Button) findViewById(R.id.btn_search);
		editTextSearch = (EditText) findViewById(R.id.edit_search);
		mPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.pulltorefresh_indent);
	}

	private void initPullToRefreshListView() {
		mPullToRefreshListView.setMode(PullToRefreshListView.Mode.BOTH);
		// 上拉
		mPullToRefreshListView.getLoadingLayoutProxy(false, true).setPullLabel("上拉加载更多");
		mPullToRefreshListView.getLoadingLayoutProxy(false, true).setReleaseLabel("放开加载");
		mPullToRefreshListView.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载...");
		// 下拉
		mPullToRefreshListView.getLoadingLayoutProxy(true, false).setPullLabel("下拉刷新");
		mPullToRefreshListView.getLoadingLayoutProxy(true, false).setReleaseLabel("放开加载");
		mPullToRefreshListView.getLoadingLayoutProxy(true, false).setRefreshingLabel("正在加载...");
		mPullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
				isPullDownToRefresh = true;
				pageNum = 0;// 返回显示第0页
				getIndentList();
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
				if (isLoadAllRecord) {
					showToast("到底啦！");
					onRefreshComplete();
				} else {
					isPullDownToRefresh = false;
					pageNum = pageNum + 1;// 下一页
					getIndentList();
				}
			}
		});
		mIndentAdapter = new IndentAdapter(IndentManageActivity.this, mIndents);
		mPullToRefreshListView.setAdapter(mIndentAdapter);
		mPullToRefreshListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				deleteIndentByOrderno(position - 1);
			}
		});
	}

	private void initListener() {
		btnBack.setOnClickListener(this);
		btnAdd.setOnClickListener(this);
		btnDelete.setOnClickListener(this);
		btnSearch.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			finish();
			break;
		case R.id.btn_add:
			Intent intent = new Intent(this, AddIndentActivity.class);
			startActivity(intent);
			break;
		case R.id.btn_delete:
			editTextSearch.setText("");
			break;
		case R.id.btn_search:
			Toast.makeText(this, "开发中。。。查询。。。", Toast.LENGTH_SHORT).show();
			break;
		}
	}

	/**
	 * 获取订单列表
	 */
	private void getIndentList() {
		showLoadingDialog("数据加载中……");
		String url = myApplication.url + "listOrder.htm";
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("accessToken", "5C9.yx0S");
		params.addQueryStringParameter("pageNum", "" + pageNum);
		params.addQueryStringParameter("numPerPage", "" + numPerPage);
		new HttpUtils().send(HttpMethod.POST, url, params, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				Log.i("Long", arg0.result);
				try {
					JSONObject jsonObject = new JSONObject(arg0.result);
					if (jsonObject.has("code") && "0".equals(jsonObject.getString("code"))) {
						List<Indent> mIndentTemp = GsonUtil.getGson().fromJson(jsonObject.getString("list"), new TypeToken<List<Indent>>() {
						}.getType());
						if (mIndentTemp.size() < numPerPage) {
							isLoadAllRecord = true;
						} else {
							isLoadAllRecord = false;
						}
						if (isPullDownToRefresh) {
							mIndents.clear();
						}
						for (Indent mIndent : mIndentTemp) {
							mIndents.add(mIndent);
						}
						onRefreshComplete();
					} else {
						showToast(jsonObject.getString("msg"));
					}
					dismissLoadingDialog();
				} catch (Exception e) {
					e.printStackTrace();
					dismissLoadingDialog();
				}
			}

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				arg0.printStackTrace();
				dismissLoadingDialog();
			}
		});
	}

	private void onRefreshComplete() {
		if (isLoadAllRecord) {
			showToast("加载完全部数据！");
		}
		mIndentAdapter.notifyDataSetChanged();
		mPullToRefreshListView.onRefreshComplete();
	}

	public void onRefresh() {
		mIndentAdapter.notifyDataSetChanged();
	}

	/**
	 * 删除订单
	 */
	private void deleteIndentByOrderno(final int position) {
		showLoadingDialog("删除订单中……");
		String url = myApplication.url + "cancelOrder.htm";
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("accessToken", "5C9.yx0S");
		params.addQueryStringParameter("orderno", "" + mIndents.get(position).getNumber());
		new HttpUtils().send(HttpMethod.POST, url, params, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				Log.i("Long", arg0.result);
				try {
					JSONObject jsonObject = new JSONObject(arg0.result);
					if (jsonObject.has("code") && "0".equals(jsonObject.getString("code"))) {
						mIndents.remove(position);
						mIndentAdapter.notifyDataSetChanged();
					}
					showToast(jsonObject.getString("msg"));
					dismissLoadingDialog();
				} catch (Exception e) {
					e.printStackTrace();
					dismissLoadingDialog();
				}
			}

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				arg0.printStackTrace();
				dismissLoadingDialog();
			}
		});
	}
}
